<template>
  <div class="app-container">
    <el-container>
      <el-aside
        class="full-height"
        style="box-shadow: 1px 1px 5px #f0f0f0"
        width="480px"
      >
        <div class="content">
          <div class="day-current color-white">
            <div class="day-current-inner">
              <div class="title d-flex font16">
                <span>
                  <i class="iconfont icon-weizhi"></i>
                  邢台
                </span>
                <span
                  class="mlauto"
                  style="
                    padding: 0 16px;
                    background: rgba(0, 0, 0, 0.4);
                    border-radius: 16px;
                  "
                >
                  {{
                    weatherData.data[0].date +
                    '&nbsp;&nbsp;' +
                    weatherData.data[0].week
                  }}
                </span>
              </div>
              <div class="weather d-flex">
                <div class="weather-l d-flex flex-column mr12">
                  <img
                    :src="weatherData.data[0].pic"
                    :title="weatherData.data[0].wea"
                  />
                  <span class="font24 color-white">
                    {{ weatherData.data[0].wea }}
                  </span>
                </div>
                <div class="weather-r d-flex flex-column text-align-left ml12">
                  <div class="h24"></div>
                  <span class="font-bold font18">
                    {{ weatherData.data[0].tem_night }}℃ ~
                    {{ weatherData.data[0].tem_day }}℃
                  </span>
                  <div class="h12"></div>
                  <span>{{ weatherData.data[0].win }}</span>
                  <div class="h12"></div>
                  <span>{{ weatherData.data[0].win_speed }}</span>
                </div>
              </div>
            </div>
          </div>
          <div class="days d-flex">
            <div
              v-for="(item, index) in weatherData.data.slice(1)"
              :key="index"
              class="day d-flex flex-column flex-1 align-items-center"
            >
              <span class="h12"></span>
              <span>{{ item.week }}</span>
              <span class="mt4">{{ item.date.substr(5) }}</span>
              <span class="h12"></span>
              <span class="font-bold font16 mt12">{{ item.tem_day }}℃</span>
              <span class="h12"></span>
              <span class="font-bold font16 mt12">{{ item.tem_night }}℃</span>
              <span class="h12"></span>
              <img :src="item.pic" style="width: 32px" :title="item.wea" />
              <span class="mt4">{{ item.win }}</span>
              <span class="mt4">{{ item.win_speed }}</span>
            </div>
          </div>
        </div>
      </el-aside>
      <el-main class="full-height pt0" style="padding-top: 0">
        <div class="tip">
          <el-date-picker
            v-model="params.gdate"
            align="center"
            end-placeholder="结束日期"
            range-separator="~"
            start-placeholder="开始日期"
            type="daterange"
            value-format="yyyy-MM-dd"
          />
          <el-button
            class="ml12"
            icon="el-icon-search"
            type="primary"
            @click="weatherDaily"
          >
            查询
          </el-button>
          <el-button
            class="ml12"
            icon="el-icon-download"
            type="success"
            @click="handleExport"
          >
            导出
          </el-button>
          <el-button
            class="ml12"
            icon="el-icon-plus"
            type="danger"
            @click="handleAddCell"
          >
            导入
          </el-button>
        </div>
        <div class="h12"></div>
        <el-tabs v-model="activeName" type="card">
          <el-tab-pane label="趋势" name="first">
            <ve-line
              v-if="results.length > 0"
              :data="chartData"
              :extend="chartExtend"
              :height="chartHeight"
              :settings="chartSettings"
            />
            <el-empty v-else description="暂无任何记录" />
          </el-tab-pane>
          <el-tab-pane label="列表数据" name="second">
            <el-table border :data="results" :height="height" stripe>
              <el-table-column
                align="center"
                label="编号"
                type="index"
                width="60"
              />
              <el-table-column
                align="center"
                label="日期"
                prop="gdate"
                show-overflow-tooltip
              />
              <el-table-column
                align="center"
                label="日平均温度"
                prop="temp_avg"
              />
              <el-table-column
                align="center"
                label="日最低温度"
                prop="temp_low"
              />
              <el-table-column
                align="center"
                label="日最高温度"
                prop="temp_high"
              />
              <el-table-column
                align="center"
                label="日降雨量"
                prop="rainfall"
              />
              <el-table-column align="center" label="风速" prop="wind_spd" />
              <el-table-column align="center" label="日辐射" prop="radiation" />
              <el-table-column align="center" label="湿度" prop="humidity" />
              <el-table-column align="center" label="ET0" prop="et0" />
              <el-table-column align="center" label="操作" width="100">
                <template #default="{ row }">
                  <el-link
                    class="mr12"
                    icon="el-icon-edit"
                    type="primary"
                    @click="handleEdit(row)"
                  >
                    修改
                  </el-link>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
        <edit ref="edit" />
        <el-dialog
          title="载入数据文件"
          :visible.sync="dialogVisible"
          width="800px"
        >
          <el-empty
            v-if="tableData.length === 0"
            description="暂无任何计算结果"
          >
            <file-upload
              :action="uploadUrl"
              :name="name"
              @onSuccess="onSuccess"
            />
          </el-empty>
        </el-dialog>
      </el-main>
    </el-container>
  </div>
</template>

<script>
  import Edit from './components/Edit'
  import {
    deepClone,
    getCurrentDate,
    getNextDate,
    removeEmptyField,
  } from '@/utils/index'
  import FileUpload from '@/components/FileUpload'
  import { weather, weatherDaily } from '@/api/device'
  import { mapGetters } from 'vuex'
  import * as XLSX from 'xlsx'
  export default {
    components: {
      Edit,
      FileUpload,
    },
    data() {
      const currentDate = getCurrentDate()
      return {
        qxz: '0201.0007.2403004379',
        params: {
          page: 1,
          pagesize: 1000,
          gdate: [getNextDate(currentDate, -30), currentDate],
        },
        activeName: 'first',
        height: 'calc(100vh - 284px)',
        dialogVisible: false,
        tableData: [],
        uploadUrl: 'https://api.zesi.com.cn/idata/util/upload',
        name: 'awc',
        chartSettings: {},
        chartHeight: 'calc(100vh - 234px)',
        chartExtend: {
          series: {
            showSymbol: false,
          },
          grid: {
            left: '2%',
            right: '2%',
            bottom: '6%',
            top: '6%',
            containLabel: true,
          },
        },
        results: [],
        weatherData: {
          city: '',
          update_time: '',
          data: [{}],
        },
      }
    },
    computed: {
      ...mapGetters(['project']),
      chartData() {
        const fields = [
          { namekey: 'gdate', name: '日期' },
          { namekey: 'temp_avg', name: '日平均温度(℃)' },
          { namekey: 'temp_low', name: '日最低温度(℃)' },
          { namekey: 'temp_high', name: '日最高温度(℃)' },
          { namekey: 'rainfall', name: '降雨量(mm)' },
          { namekey: 'wind_spd', name: '风速(m/s)' },
          { namekey: 'radiation', name: '辐射(MJ/m²d)' },
          { namekey: 'humidity', name: '相对湿度(%RH)' },
        ]
        const results = deepClone(this.results)
        return {
          columns: fields.map((val) => val.name),
          rows: results.map((item) => {
            const temp = {}
            fields.forEach((citem) => {
              temp[citem.name] = item[citem.namekey]
            })
            return temp
          }),
        }
      },
    },
    created() {
      this.weather()
      this.weatherDaily()
    },
    methods: {
      async weather() {
        const { data } = await weather(this.project.id)
        this.weatherData = data
      },
      async weatherDaily() {
        let params = { serialno: this.qxz }
        params = removeEmptyField(Object.assign(params, this.params))
        const {
          data: { data },
        } = await weatherDaily(params)
        this.results = data
      },
      onSuccess(response) {
        const { errorCode, msg, data } = response
        if (errorCode !== 0) {
          this.$message({
            message: (msg && `上传失败，失败原因：${msg}`) || '上传失败',
            type: 'error',
          })
          this.$emit('onError', data)
        } else {
          this.$baseMessage('操作成功', 'success')
          this.tableData = data
        }
      },
      handleExport() {
        let title = [
          { namekey: 'gdate', name: '日期' },
          { namekey: 'temp_avg', name: '日平均温度(℃)' },
          { namekey: 'temp_low', name: '日最低温度(℃)' },
          { namekey: 'temp_high', name: '日最高温度(℃)' },
          { namekey: 'rainfall', name: '降雨量(mm)' },
          { namekey: 'wind_spd', name: '风速(m/s)' },
          { namekey: 'radiation', name: '辐射(MJ/m²d)' },
          { namekey: 'humidity', name: '相对湿度(%RH)' },
        ]
        let data = []
        this.results.forEach((item) => {
          let temp = []
          title.forEach((citem) => {
            temp.push(item[citem.namekey])
          })
          data.push(temp)
        })
        data.unshift(title.map((item) => item.name))
        // 将数据转换为工作表
        const ws = XLSX.utils.aoa_to_sheet(data)

        // 创建工作簿并添加工作表
        const wb = XLSX.utils.book_new()
        XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')

        // 生成Excel文件并导出
        XLSX.writeFile(wb, 'output.xlsx')
      },
      handleAddCell() {
        this.dialogVisible = true
      },
      handleEdit(row) {
        this.$refs.edit.show(row)
      },
    },
  }
</script>

<style lang="scss" scoped>
  .content {
    height: 720px;
    text-align: center;
  }
  .day {
    span {
      display: inline-block;
    }
    img {
      margin: 8px 0;
    }
    &-current {
      background-image: url('https://api.zesi.com.cn/storage/project/20200620/a8ed0455a523a4a933f6393ac5263c48.jpg');
      background-repeat: no-repeat;
      background-size: cover;
      border-radius: 16px 16px 0 0;

      &-inner {
        height: 240px;
        padding: 24px;
        background: rgba(94, 165, 224, 0.8);
        border-radius: 16px 16px 0 0;
        .title {
          height: 32px;
          line-height: 32px;
          span {
            &:first-child {
              color: #fff;
            }
          }
        }
      }
    }
  }
</style>
